package cn.edu.sjtu.se.dslab.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.edu.sjtu.se.dslab.project.Project;
import cn.edu.sjtu.se.dslab.rhapsody.parse.XmiDocument;
import cn.edu.sjtu.se.dslab.rhapsody.service.ActorDeviceGenerator;
import cn.edu.sjtu.se.dslab.rhapsody.service.RhapsodyFileService;
import cn.edu.sjtu.se.dslab.service.IDesignPatternComponentService;
import cn.edu.sjtu.se.dslab.service.IProjectService;

@Controller
@RequestMapping(value="/rhapsody")
public class RhapSodyFileController {
	private static final Logger logger = Logger
			.getLogger(RhapSodyFileController.class);

	@Resource(name = "projectService")
	IProjectService projectService;

	@Resource(name = "designPatternComponentService")
	IDesignPatternComponentService designPatternComponentService;

	@Resource(name = "rhapsodyFileService")
	RhapsodyFileService rhapsodyFileService;
	
	@Resource(name="actorDeviceGenerator")
	ActorDeviceGenerator actorDeviceGenerator;

	@RequestMapping(value = "/{projectId}/upload", method = RequestMethod.POST)
	@ResponseBody
	public Map<String,String> addRhapsodyFile(//@RequestParam long projectId,
			@PathVariable(value = "projectId") long projectId,
			@RequestParam MultipartFile rhapsody_file) throws IOException {
		Map<String, String> resultMap = new HashMap<String,String>();
		try{
			rhapsodyFileService.uploadRhapsodyXmiFile(projectId, rhapsody_file);
			resultMap.put("result", Boolean.TRUE.toString());
		}catch(Exception ex){
			ex.printStackTrace();
			resultMap.put("result", Boolean.FALSE.toString());
		}
		return resultMap;
	}

	@RequestMapping(value = "/{projectId}/mapDesignPattern", method = RequestMethod.POST)
	@ResponseBody
	public Map<String,String> mapDesignPattern(//@RequestParam long projectId) {
		@PathVariable(value = "projectId") long projectId){
		Map<String, String> resultMap = new HashMap<String,String>();
		try{
			Project project = projectService.getProjectById(projectId);
			if (null == project) throw new NullPointerException("No such project id=" + projectId);
			logger.info("Rhapsody path :" + project.getRhapsodyFile());
			XmiDocument doc = new XmiDocument(project.getRhapsodyFile());
			
			rhapsodyFileService.saveXmiParseResult(projectId);
			
			//XmiConverter converter = new XmiConverter(doc);
			//converter.mapToProject(projectId);
			
			
			resultMap.put("result", Boolean.TRUE.toString());
		}catch(Exception ex){
			ex.printStackTrace();
			resultMap.put("result", Boolean.FALSE.toString());
		}
		return resultMap;
		//StringBuffer url = new StringBuffer("redirect:/project/list");
		//return url.append("?projectId=").append(projectId).toString();
	}

	@RequestMapping(value = "/{projectId}/actor", method = RequestMethod.GET)
	public void getActorFile(//@RequestParam long projectId,
			@PathVariable(value = "projectId") long projectId,
			HttpServletResponse response) throws IOException {
		
		//String actorFilePath = rhapsodyFileService.generateActorFile(projectId);
		String actorFilePath = actorDeviceGenerator.generateFile(projectId);
		
		File actorFile = new File(actorFilePath);
		InputStream is = new FileInputStream(actorFile);
		response.setContentType("application/octet-stream");
		response.setContentLength((int) actorFile.length());
		String headerKey = "Content-Disposition";
		String headerValue = String.format("attachment;filename=\"%s\"",
				actorFile.getName());
		System.out.println(actorFile.getName());
		response.setHeader(headerKey, headerValue);
		IOUtils.copy(is, response.getOutputStream());
		response.flushBuffer();
	}

}
